package net.palla.biblio.client;

import net.palla.biblio.shared.Author;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class AuthorDetailPanel extends DialogBox {

	private BiblioServiceAsync service;
	private Author author;
	
	private static AuthorDetailPanelUiBinder uiBinder = GWT
			.create(AuthorDetailPanelUiBinder.class);

	interface AuthorDetailPanelUiBinder extends
			UiBinder<Widget, AuthorDetailPanel> {
	}

	public AuthorDetailPanel(BiblioServiceAsync service, Author author) {
		this.add(uiBinder.createAndBindUi(this));
		this.service = service;
		this.author = author;
		if (author != null)
			tbName.setText(author.getName());
	}

	@UiField TextBox tbName;
	@UiField Button btnSave;
	@UiField Button btnCancel;

	@UiHandler("btnCancel")
	void onBtnCancelClick(ClickEvent e) {
		hide();
	}

	@UiHandler("btnSave")
	void onBtnSaveClick(ClickEvent e) {
		if (author == null)
			author = new Author();
		author.setName(tbName.getText());
		try {
			service.saveAuthor(author, new AsyncCallback<Author>() {
				
				@Override
				public void onSuccess(Author result) {
					hide();				
				}
				
				@Override
				public void onFailure(Throwable caught) {
					Window.alert(caught.getMessage());
				}
			});
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}
	
}
